package edu.zut.cs.network.exercise.bank.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import edu.zut.cs.network.exercise.bank.dao.BankDao;
import edu.zut.cs.network.exercise.bank.entity.Bank;
import edu.zut.cs.network.exercise.bank.util.DBUtil;


public class BankDaoImpl implements BankDao {

	static Logger logger = LogManager.getLogger(BankDaoImpl.class);
	
	public void add(Bank bank) {

		try {
//			DBUtil.getConnection();
			String sql = "insert into bank(Name,Age,Money) values(?,?,?)";
			Object[] objects = {bank.getName(),bank.getAge(),bank.getMoney()};
			DBUtil.update(sql, objects);
			DBUtil.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	public void delete(Bank bank) {

		try {

			String sql = "delete from bank where name=?";
			Object[] object = {bank.getName()};
			DBUtil.update(sql, object);
			DBUtil.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	public Bank findByName(String name) {
		
		try {

			String sql = "SELECT NAME,AGE,MONEY FROM bank WHERE Name=?";
			Object[] object = {name};
			ResultSet set = DBUtil.query(sql, object);
			while(set.next()) {
				String bName = set.getString(1);
				String bAge = set.getString(2);
				String bMoney = set.getString(3);
				Bank bank = new Bank(bName, bAge, bMoney);
				return bank;
			}
			DBUtil.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	public List<Bank> queryall() {

		
		List<Bank> banklist = new ArrayList<Bank>();
		try {

			String sql = "SELECT NAME,AGE,MONEY FROM bank";
			Object[] object = {};
			ResultSet set = DBUtil.query(sql,object);
			while(set.next()) {
				Bank bank = new Bank();
				bank.setName(set.getString(1));
				bank.setAge(set.getString(2));
				bank.setMoney(set.getString(3));
				banklist.add(bank);
			}
			DBUtil.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return banklist;
	}

	public void upDate(Bank bank) {
		
		String sql = "UPDATE bank SET Age=?,Money=? where Name=?";
		Object[] objects = {bank.getAge(),bank.getMoney(),bank.getName()};
		logger.info(bank.money);
		try {

			DBUtil.update(sql, objects);
			DBUtil.close();
		} catch (SQLException e) {

			e.printStackTrace();
		}
		
	}

}
